package com.qg.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qg.dto.ReturnResult;
import com.qg.dto.ReturnResultUtils;
import com.qg.pojo.QgUser;
import com.qg.service.LocalQgUserService;
import com.qg.service.QgUserService;
import com.qg.util.*;
import com.qg.vo.QgUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class LovalQgUserServiceImpl implements LocalQgUserService {
    @Reference
    private QgUserService qgUserService;

    @Autowired
    private RedisUtil redisUtil;
    @Override
    /***
     * 根据用户名和密码生成token
     * @param phone
     * @param password
     * @return
     */
    public QgUserVo UserLogin(String phone, String password) throws Exception {
        QgUser qgUser=qgUserService.queryLoginPhoneAndPwd(phone,password);

        QgUserVo qgUserVo=new QgUserVo();
        if(EmptyUtils.isEmpty(qgUser)){
            return null;
        }
        String key=null;
        String  tokenkey=redisUtil.getStr(qgUser.getId());
        if (EmptyUtils.isEmpty(tokenkey)){
            String userJson=JSON.toJSONString(qgUser);
            key=MD5.getMd5(qgUser.getId(),16);
            redisUtil.setStr(Canstants.token+key,userJson,Canstants.timeOut);
            redisUtil.setStr(qgUser.getId(),Canstants.token+key);
        }
        BeanUtils.copyProperties(qgUser,qgUserVo);

        String userJson=redisUtil.getStr(tokenkey);
        qgUserVo.setToken(Canstants.token+key);
        return qgUserVo;
    }

    @Override
    public ReturnResult removeToken(String token) throws Exception {
        String qgUserJson=redisUtil.getStr(token);
        QgUser qgUser= JSONObject.parseObject(qgUserJson,QgUser.class);
        redisUtil.del(token);
        redisUtil.del(qgUser.getId());
        return  ReturnResultUtils.resultSuccess();
    }

}

